import React, { Component } from 'react';
import { Form, Input } from 'antd';
import CascadeDatePicker from '../CascadeDatePicker/index.jsx';

const FormItem = Form.Item;
const EditableContext = React.createContext();

const EditableRow = ({ form, index, ...props }) => {
  return (
    <EditableContext.Provider value={form}>
      <tr {...props}></tr>
    </EditableContext.Provider>
  );
};

export const EditableFormRow = Form.create()(EditableRow);


export class EditableCell extends Component {

  currentEdit = null

  state = {
    editing: false
  }

  handleClickOutside = (e) => {
    const { editing } = this.state;
    if (editing && this.cell !== e.target && !this.cell.contains(e.target)) {
      this.save();
    }
  }

  save = () => {
    const { record, handleSave } = this.props;
    this.form.validateFields((error, values) => {
      if (error) {
        return;
      }
      this.toggleEdit();
      handleSave({ ...record, ...values });
    });
  }

  toggleEdit = () => {
    const editing = !this.state.editing;
    this.setState({ editing }, () => {
      if (editing) {
        this.currentEdit.focus();
      }
    });
  }

  getEditComp = (type) => {
    const commonProps = {
      ref: (node) => (this.currentEdit = node)
    };
    const strategy = {
      input: (
        <Input
          {...commonProps}
          onPressEnter={this.save}
        />
      ),
      cascadeDatePicker: (
        <CascadeDatePicker></CascadeDatePicker>
      )
    };
    return strategy[type] || null;
  }

  render() {
    const { editing } = this.state;
    const {
      editable,
      dataIndex,
      title,
      record,
      index,
      handleSave,
      rules=[],
      fieldType,
      ...restProps
    } = this.props;

    return (
      <td ref={node => (this.cell = node)} {...restProps}>
        {editable ? (
          <EditableContext.Consumer>
            {(form) => {
              this.form = form;
              return (
                editing ? (
                  <FormItem style={{ margin: 0 }}>
                    {form.getFieldDecorator(dataIndex, {
                      rules,
                      initialValue: record[dataIndex],
                    })(
                      this.getEditComp(fieldType)
                    )}
                  </FormItem>
                ) : (
                  <div
                    style={{ paddingRight: 24 }}
                    onClick={this.toggleEdit}
                  >
                    {restProps.children}
                  </div>
                )
              );
            }}
          </EditableContext.Consumer>
        ) : restProps.children}
      </td>
    );
  }

  componentDidMount() {
    const { editable } = this.props;
    if (editable) {
      document.addEventListener('click', this.handleClickOutside, true);
    }
  }

  componentWillUnmount() {
    const { editable } = this.props;
    if (editable) {
      document.removeEventListener('click', this.handleClickOutside, true);
    }
  }
}